package com.weiqiao.mall.rest;


import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.aop.log.Log;
import com.weiqiao.mall.domain.CardCommodityEntity;
import com.weiqiao.mall.domain.TeamCommodityEntity;
import com.weiqiao.mall.domain.TeamEntity;
import com.weiqiao.mall.service.ICardCommodityService;
import com.weiqiao.mall.service.ITeamCommodityService;
import com.weiqiao.mall.service.vo.UpdateTeamCommodityDistributorInfoVO;
import com.weiqiao.mall.service.vo.UpdateTeamCommodityVO;
import com.weiqiao.utils.*;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 *
 */
@RestController
@RequestMapping(value = "api")
public class CardCommodityController {

    @Autowired
    private ICardCommodityService cardCommodityService;

    @Autowired
    private ITeamCommodityService teamCommodityService;

    /**
     * 产品管理，添加信用卡产品
     * @param commodity
     * @return
     */
    @RequestMapping("/add-card-commodity")
    public ResponseEntity addCardCommodity(@RequestBody CardCommodityEntity commodity) {
        if (StringUtil.isBlank(commodity.getCommodity_id())) {
            commodity.setCommodity_id("" + System.currentTimeMillis());
            commodity.setCreate_date("" + System.currentTimeMillis());
        }
        cardCommodityService.addCardCommodity(commodity);
        // 若省长发生了变动，不相关联的省长团队信息删除
        teamCommodityService.delTeamCommodity(commodity.getCompany_id(), commodity);
        // 同步更新团队产品表基本信息
        Bson filter = new Document("commodity_id", commodity.getCommodity_id());
        Document update = updateTeamCommodity(commodity);
        teamCommodityService.updateCommodity(commodity.getCompany_id(), filter, update);
        return new ResponseEntity(true, HttpStatus.OK);
    }

    /**
     * 更新团队商品基本信息
     * @param commodity
     * @return
     */
    private Document updateTeamCommodity(CardCommodityEntity commodity) {
        Document update = new Document("name", commodity.getName());
        update.append("variety_id", commodity.getVariety_id());
        update.append("variety_name", commodity.getVariety_name());
        update.append("second_variety_id", commodity.getSecond_variety_id());
        update.append("state", commodity.getState());
        update.append("bank_id", commodity.getBank_id());
        return update;
    }

    @Log("商品管理列表")
    @GetMapping("/card-commodity-list")
    public ResponseEntity cardCommodityList(HttpServletRequest request, Pageable pageable) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        Document doc = this.getCommoditysFilter(request);
        //查询总记录数
        int total = cardCommodityService.countCommodity(company_id, doc);
        //商品列表
        List<CardCommodityEntity> commodityList = cardCommodityService.findCommoditys(company_id, doc, pageable);
        return new ResponseEntity(PageUtil.toPage(commodityList, total), HttpStatus.OK);
    }

    // 商品列表查询条件
    private Document getCommoditysFilter(HttpServletRequest request) {
        // 省长产品使用，产品表
        String operator_id = request.getParameter("operator_id");
        // 团长产品使用，团队产品表
        String teamId = request.getParameter("team_id");
        String team_operator_id = request.getParameter("team_operator_id");
        // 基本查询条件
        String tabId = request.getParameter("tabId");
        String name = request.getParameter("name");
        String variety_id = request.getParameter("variety_id");
        String state = request.getParameter("state");
        String supplier_name = request.getParameter("supplier_name");
        String time = request.getParameter("time");
        String ids = request.getParameter("commodity_ids");
        List<String> commodity_Ids = StringUtils.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        // 标签
        String label_brand_id = request.getParameter("label_brand_id");
        //查询条件
        Document doc = new Document();
        if (CollectionUtils.isNotEmpty(commodity_Ids)) {
            //导出勾选时获取勾选的商品ids
            doc.append("commodity_id", new Document("$in", commodity_Ids));
            return doc;
        }
        // 标签不为空
        if (!StringUtil.isBlank(label_brand_id)) {
            doc.append("label_brand_ids", label_brand_id);
        }
        if (!StringUtil.isBlank(name)) {
            doc.append("name", new Document("$regex", name));
        }
        if (!StringUtil.isBlank(state)) {
            doc.append("state", Integer.parseInt(state));
        }
        if (!StringUtil.isBlank(variety_id)) {
            String[] varietyIdList = variety_id.split(",");
            doc.append("variety_id", varietyIdList[0]);
            if (varietyIdList.length > 1) doc.append("second_variety_id", varietyIdList[1]);
        }
        if (!StringUtil.isBlank(supplier_name)) {
            doc.append("supplier_name", new Document("$regex", supplier_name));
        }
        if (!StringUtil.isBlank(time) && time.split("~").length > 1) {
            doc.append("create_date", new Document("$gte", "" + DateUtil.getTime(time.split("~")[0])).append("$lte",
                    "" + DateUtil.getTime(time.split("~")[1])));
        }
        // 大范围的查询条件放在最后面
        if ("2".equals(tabId)) {
            doc.append("state", 0);
        } else if ("3".equals(tabId)) {
            doc.append("state", 1);
        } else if ("4".equals(tabId) ) {
            // 省长产品，商品省长不为空
            doc.append("operator_list", new Document("$gt", new ArrayList<>()));
            // 产品表.根据省长id进行查询
            if (StringUtil.isInteger(operator_id)) {
                doc.append("operator_list.user_id", Integer.parseInt(operator_id));
            }
        } else if ("5".equals(tabId)) {
            // 团队产品表.根据团队id进行查询，团长查看
            if (!StringUtil.isBlank(teamId)) {
                doc.append("team_id", teamId);
            }
            // 团队产品表.根据省长id进行查询，省长查看
            if (StringUtil.isInteger(team_operator_id)) {
                doc.append("operator_id", Integer.parseInt(team_operator_id));
            }
            // 系统管理员，看所有
        }
        doc.append("delete_flag", 0);
        return doc;
    }

    @Log("获取当前商品详细信息")
    @PostMapping("/get-card-commodity")
    public ResponseEntity getCardCommodity(HttpServletRequest request) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        String commodity_id = request.getParameter("commodity_id");
        return new ResponseEntity(cardCommodityService.findCommodityById(commodity_id, company_id), HttpStatus.OK);
    }

    @Log("删除当前商品信息")
    @PostMapping("/del-card-commodity")
    public ResponseEntity delCardCommodity(HttpServletRequest request) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        String commodity_id = request.getParameter("commodity_id");
        // 同步更新团队商品表
        teamCommodityService.detCardCommodity(commodity_id, company_id);
        return new ResponseEntity(cardCommodityService.detCardCommodity(commodity_id, company_id), HttpStatus.OK);
    }

    @Log("修改宝贝标签")
    @RequestMapping("/update-card-commodity-label")
    public ResponseEntity updateCommodityLabel(HttpServletRequest request) {
        //公司id
        int companyId = MallUtil.getCompanyId(request);
        // 更改的标签集合，传来的是字串，需要转为集合
        String label = request.getParameter("labels");
        List<String> labels = StringUtil.isBlank(label) ? new ArrayList<>() : Arrays.asList(label.split(","));
        // 需要修改的商品集合，传来的是字串，需要转为集合
        String ids = request.getParameter("commodity_ids");
        List<String> commodity_Ids = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        cardCommodityService.updateCardCommodityLabel(commodity_Ids, companyId, labels);
        return new ResponseEntity(true, HttpStatus.OK);
    }

    @Log("批量上，下架")
    @RequestMapping("/up-down-card-commodity")
    public ResponseEntity upDownCommodity(HttpServletRequest request) {
        //公司id,商品ids,type类型0-上架 1-下架
        int company_id = MallUtil.getCompanyId(request);
        String type = request.getParameter("type");
        String ids = request.getParameter("commodity_ids");
        List<String> commodity_Ids = StringUtil.isBlank(ids) ? new ArrayList<>() : Arrays.asList(ids.split(","));
        if (!StringUtil.isInteger(type)) {
            return new ResponseEntity(false, HttpStatus.OK);
        }
        Bson filter = Filters.and(Filters.eq("company_id", company_id), Filters.in("commodity_id", commodity_Ids));
        Document doc = new Document("state", Integer.valueOf(type));
        // 更新产品表状态
        cardCommodityService.updateCommodity(company_id, filter, doc);
        // 同步更新团队产品表状态
        teamCommodityService.updateCommodity(company_id, filter, doc);

        return new ResponseEntity(true, HttpStatus.OK);
    }

    /**
     * 用于宝贝分类的商品列表显示
     *
     * @param request
     * @param pageable
     * @return
     */
    @Log("分页获取商品管理列表")
    @PostMapping("/get-commodity-page")
    public ResponseEntity getCommodityPage(HttpServletRequest request, Pageable pageable) {
        List<String> paramList = new ArrayList<>();
        int companyId = MallUtil.getCompanyId(request);
        String label_id = MallUtil.getString(request, "label_id", "");
        paramList.add(label_id);
        Document query = new Document();
        query.append("delete_flag", 0);
        query.append("label_brand_ids", new Document("$in", paramList));
        List<CardCommodityEntity> commoditys = cardCommodityService.findCommoditys(companyId, query);
        paramList.clear();
        if (CollectionUtils.isNotEmpty(commoditys)) {
            commoditys.forEach(item -> paramList.add(item.getCommodity_id()));
        }
        Document doc = this.getCommoditysFilter(request);
        doc.append("state", 0);
        if (CollectionUtils.isNotEmpty(paramList)) {
            doc.append("commodity_id", new Document("$nin", paramList));
        }
        //查询总记录数
        int total = cardCommodityService.countCommodity(companyId, doc);
        //当前商品列表
        List<CardCommodityEntity> list = cardCommodityService.findCommoditys(companyId, doc, pageable);
        return new ResponseEntity(PageUtil.toPage(list, total), HttpStatus.OK);
    }


    @Log("宝贝标签-保存右侧宝贝与标签关联关系")
    @PostMapping(value = "/label-shelf-save-pro")
    public ResponseEntity saveProductAndLabelData(HttpServletRequest request) {
        return cardCommodityService.saveCheckProduct(request);
    }



    @Log("团队产品列表")
    @GetMapping("/team-commodity-list")
    public ResponseEntity teamCommodityList(HttpServletRequest request, Pageable pageable) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        Document doc = this.getCommoditysFilter(request);
        //查询总记录数
        int total = teamCommodityService.countCommodity(company_id, doc);
        //商品列表
        List<TeamCommodityEntity> commodityList = teamCommodityService.findCommoditys(company_id, doc, pageable);
        return new ResponseEntity(PageUtil.toPage(commodityList, total), HttpStatus.OK);
    }

    @Log("管辖范围内，当前产品团队信息")
    @GetMapping(value = "/get-commodity-team-info")
    public ResponseEntity getCommodityTeamInfo(HttpServletRequest request) {
        //公司id
        int company_id = MallUtil.getCompanyId(request);
        // 产品id
        String commodity_id = request.getParameter("commodity_id");
        // 省长id
        String team_operator_id = request.getParameter("team_operator_id");
        Document filter = new Document("commodity_id", commodity_id);
        // 省长id存在时，根据省长id进行查询.否则就是管理员进行查询，查询所有
        if (StringUtil.isInteger(team_operator_id)) {
            filter.append("operator_id", Integer.parseInt(team_operator_id));
        }
        Map list = teamCommodityService.getCommodityTeamInfo(company_id, filter);
        return new ResponseEntity(list, HttpStatus.OK);
    }

    @Log("更新产品省长信息")
    @PostMapping(value = "/update-commodity-operator-info")
    public ResponseEntity updateCardCommodityOperatorInfo(@RequestBody CardCommodityEntity entity) {
        List<String> idList = Arrays.asList(entity.getCommodity_id().split(","));
        // 注意：这里是一个一个单独进行更新的。传进来的可能是个商品id集合，这个时候需要进行切割。单独更新
        for (String id: idList) {
            entity.setCommodity_id(id);
            Bson filter = Filters.eq("commodity_id", entity.getCommodity_id());
            List<Document> list = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(entity.getOperator_list())) {
                Gson gson = new Gson();
                entity.getOperator_list().forEach(info -> {
                    list.add(Document.parse(gson.toJson(info)));
                });
            }
            Document doc = new Document("operator_list", list).append("commission", entity.getCommission());
            // 若省长发生了变动，不相关联的省长团队信息删除
            teamCommodityService.delTeamCommodity(entity.getCompany_id(), entity);
            // 更新产品表省长信息
            cardCommodityService.updateCommodity(entity.getCompany_id(), filter, doc);
        }
        return new ResponseEntity(true, HttpStatus.OK);
    }

    @Log("更新产品团队信息")
    @PostMapping(value = "/update-commodity-team-info")
    public ResponseEntity updateCommodityTeamInfo(@RequestBody UpdateTeamCommodityVO entity) {
        return new ResponseEntity(teamCommodityService.updateCommodityTeamInfo(entity), HttpStatus.OK);
    }

    @Log("更新产品团队分销佣金信息")
    @PostMapping(value = "/update-commodity-distributor-info")
    public ResponseEntity updateCommodityDistributorInfo(@RequestBody UpdateTeamCommodityDistributorInfoVO entity) {
        return new ResponseEntity(teamCommodityService.updateCommodityDistributorInfo(entity), HttpStatus.OK);
    }

    @Log("导出产品列表")
    @PostMapping("/export-card-commodity-excel")
    public void exportCommodityExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int company_id = MallUtil.getCompanyId(request);
        Document doc = this.getCommoditysFilter(request);
        // 表格内容拼装
        List<Map<String, Object>> list = cardCommodityService.exportCommodityInfo(company_id, doc);
        FileUtil.downloadExcel(list, response);
    }

}
